import React, {useCallback, useEffect, useMemo, useRef, useState} from "react"
import {
    addDirectSaleOrderItem,
    AddDirectSaleOrderItemRequest,
    deleteDirectSaleOrderItem,
    getDirectSaleOrderDetail,
    DirectSaleOrderDetail,
    DirectSaleOrderItem,
    submitDirectSaleOrder,
    updateDirectSaleOrderItemAmount,
    findAllGoodsWithHistoryOrder,
    GoodsSummaryWithPrice, payDirectSaleOrder
} from "../../apis/DirectSaleOrderApi";
import {Button, Col, Descriptions, Input, InputNumber, List, Popover, Row, Table, TableColumnProps, theme} from "antd";
import {OffsetDateTime} from "@js-joda/core";
import {convertAntdTableToExcel, ExportedColumnProps, useTableSearchTextColumnProps} from "../../utils/AntdTableUtils";
import AuthorizationResource from "../../components/AuthorizationResource";
import {DeleteOutlined} from "@ant-design/icons";
import {NumberIdAndName} from "../../types/BasicModels";
import {getAllGoodsBrand} from "../../apis/GoodsBrandsApi";
import {getAllGoodsCategories} from "../../apis/GoodsCategoriesApi";
import DataPageLayout from "../../components/DataPageLayout";
import ArrayUtils from "@zxy-cn/array-utils";
import SingleInputPopover from "../../components/SingleInputPopover";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../../components/LoadableButton";
import {saveWorkbookTo} from "../../utils/FileSaver";
import GoodsTable from "../../components/GoodsTable";
import {MarketOrderItem} from "../../apis/MarketOrderApi";
import {asyncConfirm} from "../../utils/AntdModalUtils";
import EditOrderItemWithPriceRow from "../../components/EditOrderItemWithPriceRow";
import {useGlobalStyle} from "../../global.style";
import PaidRecordPopover from "../../components/PaidRecordPopover";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";


export interface pageProps {
    id: number
}

const myPath = "directSales/orders/{id}"

const DirectSaleOrderDetailPage: React.FC<pageProps> = ({id}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<DirectSaleOrderDetail>()

    async function loadData() {
        setLoading(true)
        getDirectSaleOrderDetail(id).then(response => {
            dashboardPageStore.setTitle(myPath.replace("{id}", id.toString()), response.data.client.name + "订单")
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }

    const query = useCallback(() => {
        loadData()
    }, [id,])

    useEffect(() => {
        query()
    }, [query]);

    const [brands, setBrands] = useState<NumberIdAndName[]>([])
    const [categories, setCategories] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllGoodsBrand().then(response => setBrands(response.data))
        getAllGoodsCategories().then(response => setCategories(response.data))
    }, [])

    let searchNameTableColumnProps = useTableSearchTextColumnProps<DirectSaleOrderItem>("name", {
        placeholder: "名字"
    });
    let barcodeSearchProps = useTableSearchTextColumnProps<DirectSaleOrderItem>("barcode", {
        placeholder: "条码"
    });
    let token = theme.useToken();

    const [convertToDeliveryOrderLoading, setConvertToDeliveryOrderLoading] = useState(false)

    const columns: ExportedColumnProps<DirectSaleOrderItem>[] = [
        {
            dataIndex: "barcode",
            title: "条码",
            ...barcodeSearchProps,
            onFilter: (value, record) => {
                return record.barcode.toLowerCase().includes((value as string).toLowerCase())
            }
        },
        {
            dataIndex: "name",
            title: "名称",
            ...searchNameTableColumnProps,
            onFilter: (value, record) => {
                return record.name.toLowerCase().includes((value as string).toLowerCase())
            },
        },
        {
            dataIndex: "brand",
            title: "品牌",
            filters: brands.map(brand => {
                return {
                    text: brand.name,
                    value: brand.id,
                }
            }),
            render: it => it?.name,
        },
        {
            dataIndex: "category",
            title: "类别",
            filters: categories.map(category => {
                return {
                    text: category.name,
                    value: category.id,
                }
            }),
            render: it => it?.name,
        },
        {
            dataIndex: "amount",
            title: "库存",
        },
        {
            dataIndex: "amountInOrder",
            title: "数量",
            render: (value, record) => {
                return <div
                    style={{color: record.amountInOrder > record.amount && !data?.submitDateTime ? token.token.colorError : undefined}}>{value}</div>
            }
        },
        {
            dataIndex: "price",
            title: "零售价",
        },
        {
            dataIndex: "boxSpecification",
            title: "箱规",
        },

        {
            ignoreInExcel: true,
            title: "操作",
            render: (_, item, index) => {
                return <>
                    {/*{employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.deliveryDateTime &&
                        <SingleInputPopover title={"修改单品数量"} rules={[{type: "number", min: 0}]}
                                            onConfirm={async value => {
                                                let amount = parseInt(value);
                                                await updateDirectSaleOrderItemAmount(id, item.id, {amount})
                                                let items = Array.from(data?.items ?? []);
                                                items[index].amountInOrder = amount
                                                setData({
                                                    ...data!,
                                                    items
                                                })
                                            }} fieldName={"货品数量"} customInput={(props, ref) => {
                            return <InputNumber placeholder={props.placeholder}
                                                style={{width: "100%"}}
                                                autoFocus={props.autoFocus}
                                                min={0}
                                                defaultValue={1}/>
                        }}>
                            <Button type={"link"}>修改数量</Button>
                        </SingleInputPopover>}*/}

                    <AuthorizationResource authorities={["经销_开单"]}>
                        <Button type={"link"}
                                danger
                                onClick={() => {
                                    deleteDirectSaleOrderItem(id, item.id).then(() => {
                                        let items = Array.from(data!.items);
                                        ArrayUtils.remove(items, item)
                                        setData({
                                            ...data!,
                                            items
                                        })
                                    })
                                }}>
                            <DeleteOutlined/>
                            删除
                        </Button>
                    </AuthorizationResource>
                </>
            }

        },
    ]
    let columnsRef = useRef<ExportedColumnProps<MarketOrderItem>[]>();

    const [goodsSummaries, setGoodsSummaries] = useState<GoodsSummaryWithPrice[]>([])
    useEffect(() => {
        findAllGoodsWithHistoryOrder(id).then(res => {
            setGoodsSummaries((res.data));
        })
    }, [id])

    let globalStyle = useGlobalStyle();

    return (
        <>
            {!loading ? <Descriptions title={"订单明细"}>
                <Descriptions.Item label={"客户"}>{data?.client?.name}</Descriptions.Item>
                <Descriptions.Item label={"下单人"}>{data?.createdBy?.name}</Descriptions.Item>
                {!!data?.submitDateTime && <Descriptions.Item
                    label={"下单时间"}>{data?.submitDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item>}
                <Descriptions.Item label={"下单人"}>{data?.createdBy?.name}</Descriptions.Item>
                {!!data?.submitDateTime && <Descriptions.Item
                    label={"收款"}>
                    <>应收款</>
                    <span className={globalStyle.highlightTextColor}>{`${data!.shouldPaidPrice}，`}</span>{(() => {
                    if (!!data.paidPrice) {
                        let text: React.ReactNode;
                        if (data.paidPrice === data.shouldPaidPrice) {
                            text = "已完成"
                        } else if (data.paidTimes > 1) {
                            text = <>收款<span
                                className={globalStyle.highlightTextColor}>{data.paidTimes}</span>次，共计{data.paidTimes}次</>
                        } else {
                            text = <>{"已收款"}<span
                                className={globalStyle.highlightTextColor}>{data.paidPrice}</span></>
                        }
                        return <PaidRecordPopover orderId={id}>
                            <Button type={"link"} size={"small"}>{text}</Button>
                        </PaidRecordPopover>
                    } else {
                        return "未收款"
                    }
                })()}</Descriptions.Item>}

            </Descriptions> : null}
            <Row gutter={8} style={{margin: "12px 0"}}>
                <Col>
                    <LoadableButton onClick={async (event) => {
                        let workbook = await convertAntdTableToExcel(columns, data?.items ?? []);
                        await saveWorkbookTo(workbook, `${data?.client?.name}订单-${data?.submitDateTime ?? data!.createdDateTime.format(DATE_WITH_TIME_FORMATER)}`)
                    }}>
                        导出
                    </LoadableButton>
                </Col>
                {/*{employeeAuthorizationStore.hasAuthority("卖场_订单_转化为送货单")
                && !data?.deliveryDateTime
                && !!data?.submitDateTime ?
                    <LoadableButton onClick={async () => {
                        await convertToDeliveryOrder(id);
                        setData({...data!, deliveryDateTime: OffsetDateTime.now()})
                        navigate(`/directSaleOrders/deliveryOrders/${id}`)
                    }} loading={convertToDeliveryOrderLoading}>开送货单</LoadableButton> : undefined}*/}
                <Col>
                    {employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.submitDateTime &&
                        <LoadableButton onClick={async (event) => {
                            await asyncConfirm({
                                async onOk() {
                                    await submitDirectSaleOrder(id)
                                    loadData()
                                },
                                title: "是否确认提交",
                                content: "提交后将不可修改，且应用到库存",
                            })
                        }}>
                            提交订单
                        </LoadableButton>}
                </Col>
                <Col>
                    {employeeAuthorizationStore.hasAuthority("经销_收款") && !!data?.submitDateTime && data?.paidPrice!! < data?.shouldPaidPrice!! &&
                        <SingleInputPopover required rules={[{
                            type: "number",
                            min: 0,
                            transform: value => Number(value),
                        }, {
                            type: "number",
                            transform: value => Number(value),
                            max: data?.shouldPaidPrice ?? 0 - (data?.paidPrice ?? 0),
                            message: `已收费用${data?.paidPrice}，待收费用:${data?.shouldPaidPrice ?? 0 - (data?.paidPrice ?? 0)}`
                        }]} fieldName={"金额"} onConfirm={async (value) => {
                            let fee = parseInt(value);
                            await payDirectSaleOrder(id, {price: fee})
                            let paidPrice = data!.paidPrice + fee;
                            setData({
                                ...data!,
                                paidPrice: paidPrice,
                                paidTimes: data!.paidTimes + 1
                            })
                        }} title={"收款"} customInput={(props, ref) => {
                            return <Input ref={ref} type={"number"} {...props}/>
                        }}>
                            <Button>
                                收款
                            </Button>
                        </SingleInputPopover>}
                </Col>

                <Col>
                    {<LoadableButton onClick={async (event) => {
                        // await submitDirectSaleOrder(id)
                        // setData({...data!, submitDateTime: OffsetDateTime.now()})
                    }}>
                        打印
                    </LoadableButton>}
                </Col>
                <div style={{flexGrow: 1}}/>
                {/*TODO*/}
                {/*{employeeAuthorizationStore.hasAnyAuthority("经销_查询" ) && !!data?.deliveryDateTime &&*/}
                {/*    <Link to={`/directSaleOrders/deliveryOrders/${id}`} >*/}
                {/*        <Button type={"link"}>查看入库单</Button>*/}
                {/*    </Link>}*/}
            </Row>

            {((employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.submitDateTime) /* TODO|| (employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.submitDateTime)*/) &&
                <EditOrderItemWithPriceRow<AddDirectSaleOrderItemRequest>
                    onFinish={async (values) => {
                        return addDirectSaleOrderItem(id, values).then(() => {
                            query()
                        })
                    }} existedGoodsIds={data?.items?.map(it => it.id) ?? []} data={goodsSummaries}/>}
            <DataPageLayout leftActions={<>
            </>}>

                <GoodsTable<DirectSaleOrderItem> loading={loading}
                                                 size={"small"}
                                                 data={data?.items ?? []}
                                                 customColumns={columns => {
                                                     ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                         dataIndex: "amountInOrder",
                                                         title: "数量",
                                                         render: (value, record) => {
                                                             return <div
                                                                 style={{color: record.amountInOrder > record.amount && !data?.submitDateTime ? token.token.colorError : undefined}}>{value}</div>
                                                         }
                                                     },)
                                                     columns.push({
                                                         ignoreInExcel: true,
                                                         title: "操作",
                                                         render: (_, item, index) => {
                                                             return <>
                                                                 {employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.submitDateTime &&
                                                                     <SingleInputPopover required title={"修改单品数量"}
                                                                                         rules={[{
                                                                                             type: "number",
                                                                                             min: 0
                                                                                         }]}
                                                                                         onConfirm={async value => {
                                                                                             let amount = parseInt(value);
                                                                                             await updateDirectSaleOrderItemAmount(id, item.id, {amount})
                                                                                             let items = Array.from(data?.items ?? []);
                                                                                             items[index].amountInOrder = amount
                                                                                             setData({
                                                                                                 ...data!,
                                                                                                 items
                                                                                             })
                                                                                         }} fieldName={"货品数量"}
                                                                                         customInput={(props, ref) => {
                                                                                             return <InputNumber
                                                                                                 placeholder={props.placeholder}
                                                                                                 style={{width: "100%"}}
                                                                                                 autoFocus={props.autoFocus}
                                                                                                 min={0}
                                                                                                 defaultValue={1}/>
                                                                                         }}>
                                                                         <Button type={"link"}>修改数量</Button>
                                                                     </SingleInputPopover>}


                                                                 {(employeeAuthorizationStore.hasAuthority("经销_开单") && !data?.submitDateTime) &&
                                                                     <Button type={"link"}
                                                                             danger
                                                                             onClick={() => {
                                                                                 deleteDirectSaleOrderItem(id, item.id).then(() => {
                                                                                     let items = Array.from(data!.items);
                                                                                     ArrayUtils.remove(items, item)
                                                                                     setData({
                                                                                         ...data!,
                                                                                         items
                                                                                     })
                                                                                 })
                                                                             }}>
                                                                         <DeleteOutlined/>
                                                                         删除
                                                                     </Button>}
                                                             </>
                                                         }

                                                     },);
                                                     columnsRef.current = columns;
                                                     return columns;
                                                 }}
                                                 rowKey={"id"}>
                </GoodsTable>
            </DataPageLayout>

        </>
    )
}

export default observerDashboardPageWrapper(DirectSaleOrderDetailPage, myPath, "卖场订单详情")

